import { NextResponse } from 'next/server'
import { createAdminClient } from '@/lib/supabase'
import bcrypt from 'bcryptjs'
import { signJWT } from '@/lib/jwt'

export async function POST(req: Request) {
  try {
    const { username, password } = await req.json()

    if (!username || !password) {
      return NextResponse.json({ 
        success: false,
        message: '用户名和密码不能为空' 
      }, { status: 400 })
    }

    const supabaseAdmin = createAdminClient()

    // 1. 查询用户
    const { data: user, error: userError } = await supabaseAdmin
      .from('vertu_sys_users')
      .select('*')
      .eq('username', username)
      .single()

    if (userError || !user) {
      console.error('用户查询错误:', userError)
      return NextResponse.json({ 
        success: false,
        message: '用户名或密码错误' 
      }, { status: 401 })
    }

    // 2. 验证密码
    const passwordMatch = await bcrypt.compare(password, user.password)

    if (!passwordMatch) {
      return NextResponse.json({ 
        success: false,
        message: '用户名或密码错误' 
      }, { status: 401 })
    }

    // 3. 生成 JWT token
    const token = await signJWT({
      userId: user.id,
      username: user.username
    })

    // 4. 更新用户最后登录时间
    await supabaseAdmin
      .from('vertu_sys_users')
      .update({ updated_at: new Date().toISOString() })
      .eq('id', user.id)

    // 5. 设置 HTTP-only cookie
    const response = NextResponse.json({ 
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          username: user.username
        }
      }
    }, { status: 200 })

    // 设置 JWT token 到 cookie
    response.cookies.set('vertu-auth-token', token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: 60 * 60 * 24 * 7, // 7 天有效期
      path: '/',
      sameSite: 'lax'
    })

    return response

  } catch (error: unknown) {
    console.error('登录失败:', error)
    let errorMessage = '内部服务器错误'
    if (error instanceof Error) {
      errorMessage = error.message
    }
    return NextResponse.json({ 
      success: false,
      message: errorMessage 
    }, { status: 500 })
  }
}